package com.supreme.nettyapp.generalclient.chatclient.service;

import com.supreme.nettyapp.generalclient.chatclient.handler.ChatClientInitializer;
import com.supreme.nettyapp.generalclient.chatclient.props.ChatClientProps;
import com.supreme.nettyapp.generalclient.service.NettyClientService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Service
public class ChatClientService implements NettyClientService {

    @Resource
    private ChatClientProps chatClientProps;

    @Async(value = "nettyTask")
    @Override
    public void startNettyClient() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientInitializer());

            // Start the connection attempt.
            Channel channel = bootstrap.connect(chatClientProps.getServerHost(), chatClientProps.getServerPort()).sync().channel();

            // Read commands from the stdin.
            ChannelFuture lastWriteFuture = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }

                // Sends the received line to the server.
                lastWriteFuture = channel.writeAndFlush(line + "\r\n");

                // If user typed the 'bye' command, wait until the server closes
                // the connection.
                if ("bye".equalsIgnoreCase(line)) {
                    channel.closeFuture().sync();
                    break;
                }
            }

            // Wait until all messages are flushed before closing the channel.
            if (lastWriteFuture != null) {
                lastWriteFuture.sync();
            }
        } catch (IOException | InterruptedException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
        } finally {
            // The connection is closed automatically on shutdown.
            group.shutdownGracefully();
        }
    }

    @Override
    public void startNettyClient(String host, int port) {

    }

    @Override
    public void destroyNettyClient() {

    }
}
